package com.pn.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pn.entity.OutStore;
import com.pn.mapper.InstoreMapper;
import com.pn.mapper.OutstoreMapper;
import com.pn.mapper.ProductMapper;
import com.pn.service.OutstoreService;
import com.pn.utils.PageBean;
import com.pn.utils.Result;
import com.pn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class OutstoreServiceImpl implements OutstoreService {
    @Autowired
    private OutstoreMapper outstoreMapper;

    //添加出库单
    @Override
    public Result saveOutSore(OutStore outStore) {
        Map<String,Object> map =(Map<String, Object>) ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("userId");
        outStore.setCreateBy(userId);

        int i = outstoreMapper.insertOutStore(outStore);
        if (i > 0){
            return Result.ok("添加出库单成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"添加出库单失败");
    }

    //显示出库列表
    @Override
    public PageBean<OutStore> outstorePageList(OutStore outStore) {
        PageHelper.startPage(outStore.getPageNum(),outStore.getPageSize());
        Page<OutStore> page = outstoreMapper.selectOutstoreList(outStore);

        return new PageBean<>(page.getTotal(),page.getResult());
    }

    @Autowired
    private InstoreMapper instoreMapper;
    @Autowired
    private ProductMapper productMapper;
    //确认出库
    @Transactional
    @Override
    public Result outstoreConfirm(OutStore outStore) {
        //先查询商品的库存够不够出库
        int invent = productMapper.findInventById(outStore.getProductId());
        if (invent < outStore.getOutNum()){
            return Result.err(Result.CODE_ERR_BUSINESS,"商品的库存不足以出库");
        }


        int i = outstoreMapper.setIsOutById(outStore.getOutsId());
        if (i > 0){
            int j = instoreMapper.setInventById(outStore.getProductId(),-outStore.getOutNum());
            if (j>0){
                return Result.ok("确认出库成功！");
            }
            return Result.err(Result.CODE_ERR_BUSINESS,"确认出库失败！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"确认出库失败！");
    }
}
